#include "cxiheaderview.h"
#include <QPainter>
#include <QMouseEvent>
#include <QStyleOptionHeader>
#include <QApplication>


CxiHeaderView::CxiHeaderView(Qt::Orientation orientation, QWidget* parent)
	: QHeaderView(orientation, parent)
{
	setSectionsClickable(true);
}

CxiHeaderView::~CxiHeaderView() = default;

void CxiHeaderView::setForeColor(int logicalIndex, const QColor& foreColor)
{
	m_headerForeColor[logicalIndex] = foreColor;
	updateSection(logicalIndex);
}

void CxiHeaderView::setBackColor(int logicalIndex, const QColor& backColor)
{
	m_headerBackColor[logicalIndex] = backColor;
	updateSection(logicalIndex);;
}


void CxiHeaderView::updateHeaderColor(int logicalIndex, QStyleOptionHeader& opt) const
{
	QColor back = m_headerBackColor.value(logicalIndex, palette().color(QPalette::Button));
	QColor fore = m_headerForeColor.value(logicalIndex, palette().color(QPalette::ButtonText));
	opt.palette.setColor(QPalette::Button, back);
	opt.palette.setColor(QPalette::ButtonText, fore);
}

void CxiHeaderView::updateTextAlignment(int logicalIndex, QStyleOptionHeader& opt) const
{
	if (model())
	{
		QVariant alignVar = model()->headerData(logicalIndex, orientation(), Qt::TextAlignmentRole);
		if (alignVar.isValid()) opt.textAlignment = static_cast<Qt::Alignment>(alignVar.toInt());
	}
}

void CxiHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const
{
	QStyleOptionHeader opt;
	initStyleOption(&opt);
	opt.rect = rect;
	opt.section = logicalIndex;
	opt.text = model() ? model()->headerData(logicalIndex, orientation(), Qt::DisplayRole).toString() : QString();
	painter->save();

	//设置表头前景色背景色
	updateHeaderColor(logicalIndex, opt);
	//设置表头对齐方式
	updateTextAlignment(logicalIndex, opt);

	QApplication::style()->drawControl(QStyle::CE_Header, &opt, painter, this);
	painter->restore();
}

void CxiHeaderView::paintEvent(QPaintEvent* e)
{
	QHeaderView::paintEvent(e);
}

void CxiHeaderView::mousePressEvent(QMouseEvent* e)
{
	QHeaderView::mousePressEvent(e);
}

void CxiHeaderView::mouseMoveEvent(QMouseEvent* e)
{
	QHeaderView::mouseMoveEvent(e);
}

void CxiHeaderView::mouseReleaseEvent(QMouseEvent* e)
{
	QHeaderView::mouseReleaseEvent(e);
}